<template>
  <el-dialog title="编辑"  :close-on-click-modal="false" :visible.sync="show" class="dialog_index dialog_banner"
   :before-close="cancle">
   <el-form ref="bannerForm" v-loading="loading">
      <el-tabs type="card" v-model="activeTab">
        <el-tab-pane :label="item.site"  :name="item.site" v-for="(item)  in formList" :key="item.id">
            <el-upload class="upload-banner" action="/api/api/general/upload"   
            :on-success="(response, file, fileList) => handleBannerSuccess(response, file, fileList, item)"
             :on-error="handleBannerError" :before-upload="beforeBannerUpload"
            :show-file-list="false" accept=".png,.jpg,.jpeg  " :data="{type:'special', imageheight: imgH, imagewidth: imgW}" >
              <el-button size="small" type="primary" @click="closeDrawerDialog">图库选择</el-button>
              <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
              <div class="pop_container">
                <img v-if="item.image" :src="utils.setCdnUrl() + item.image" class="pop_image">
              </div>
            </el-upload>
            <el-form-item label="一级标题：">
              <el-input  :placeholder="'一级标题('+item.site+')（非必填项)'" v-model="item.first_title"></el-input>
            </el-form-item>
            <el-form-item label="二级标题：">
              <el-input :placeholder="'二级标题('+item.site+')（非必填项)'" v-model="item.second_title"></el-input>
            </el-form-item>
            <el-form-item label="链接：">
              <el-input :placeholder="'链接('+item.site+')（非必填项)'" v-model="item.link"></el-input>
            </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="search" @click="submitForm">保存</el-button>
      <el-button @click="cancle">取消</el-button>
    </span>
    <Drawer v-show="showDrawer" :type="'special'"  :show="showDrawer"  @closeDialog="closeDrawerDialog"></Drawer>
   </el-dialog>
</template>

<script>
import Drawer  from '@/components/Gallery/index.vue' 
import { setErrorTip } from '@/utils/index'
import { editGet, editPost } from  '@/api/index/special'

export default {
  data () {
    return {
      formList:[],
      loading: false,
      imgW: '',
      imgH: '',
      relationArticleList: [],
      activeTab: '',
      showDrawer: false
    }
  },
  components: { Drawer },
  props: {
    show: Boolean,
    closeDialog:Function,
    id: Number
  },
  watch: {
    show:function(){
      if(this.show){
        this.loading = true
        this.editGet()
      }
    }
  },
  methods: {
     // 图库选择是否显示
    closeDrawerDialog (data) {
      this.showDrawer = !this.showDrawer
      if (data && data.filePathName) { 
        let bannerList = this.formList
        // 一个个BANNER多个站点
        for(let i = 0; i < bannerList.length; i++){
          bannerList[i].image = data.filePathName
          bannerList[i].httpImage = data.filePathNameHttp
        }
      }
    },
    syncImageUrl (item) {
       let bannerList = this.formList
      // 一个个BANNER多个站点
      for(let i = 0; i < bannerList.length; i++){
        bannerList[i].image = item.image
        bannerList[i].httpImage = item.httpImage
      }
      
    },
    handleBannerSuccess (response, res, fileList, item) {
      if(response.state != 1){
        this.$message.error('上传图片失败:' + setErrorTip(response) )   
      }
      item.image = response.data.filePathName
      item.httpImage = response.data.filePathNameHttp
      this.syncImageUrl( item)
    },
    
    handleBannerError(){
      this.$message.error('上传图片失败')   
    },
    beforeBannerUpload(file){
      let that = this
      const isLt2M = file.size / 1024  <=  1024;
      if(!isLt2M){
        this.$message.error("上传图片大小不超过1M")
        return false
      }
       if(file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/jpg'){
        this.$message.error("仅支持.png/.jpg/.jpeg格式的图片")
        return false
      }
      const isSize = new Promise(function(resolve, reject){
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          let valid = true
          valid ? resolve() : reject();
          that.imgW  = img.width
          that.imgH = img.height
        }
        img.src = _URL.createObjectURL(file);
      }).then(()=>{

        return file
      }, ()=>{
        return Promise.reject()
      })
      return isSize
    },
    editGet(){
      this.loading = true
      let params = {
        banner_id: this.id
      }
      editGet(params).then(res=>{
        if(res.status == 200 ){
          let list = res.data
          this.formList = list
          if(list.length > 0){
            this.activeTab = list[0].site
          }
        }
        this.loading = false

      })
    },
    submitForm () {
      let status = this.validateForm()
      if(status){
        this.editPost()
      }
     
    },
    validateForm () {
      let list = this.formList
      let status = true
      for ( let i = 0; i < list.length; i++ ){
        if (list[i].image === '') {
          this.$message.error('站点' + list[i].site + '图片为必填项')
          status = false
          break
        }
        if (list[i].first_title.length > 100) {
          this.$message.error('站点' + list[i].site + '一级标题最多100字符')
          status = false
          break
        }
        if (list[i].second_title.length > 200) {
          this.$message.error('站点' + list[i].site + '二级标题最多200字符')
          status = false
          break
        }
        if (list[i].link.length > 200) {
          this.$message.error('站点' + list[i].site + '链接最多200字符')
          status = false
          break
        }
      }
      return status
    },
    
    editPost () {
      let list = this.formList
      let params = {
        data: JSON.stringify(list) 
      }
      editPost(params).then(res => {
        if(res.state == 1){
          this.$message.success('保存成功')   
          this.cancle()
        }
      })
    },
    cancle(){
      // this.$refs.addSiteFrom.clearValidate();
      this.$refs.bannerForm.resetFields(); // 清空原来的数据
      this.$emit('closeDialog')

    },
  },
 
}
</script>

<style>
#editProduct.dialog_banner .upload-banner .pop_container img {object-fit:cover;}
</style>